/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package reportcenter.util.custom.component;

/**
 *
 * @author renan_luz
 */
import com.jgoodies.forms.layout.CellConstraints;
import com.jgoodies.forms.layout.FormLayout;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.File;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

public class FileChooserPanel extends JComponent {

    private final JTextField fileField;
    private final JButton chooseFileButton;
    private File fileChosen;
    private JFileChooser chooser;
    private Set fileChangeListeners;

    public FileChooserPanel() {
        chooser = new JFileChooser();
        chooser.setMultiSelectionEnabled(false);
        chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);

        fileField = new JTextField();
        fileField.setEditable(false);

        chooseFileButton = new JButton("...");
        chooseFileButton.addActionListener(new Handler());

        createControl();

        fileChangeListeners = new HashSet();
    }

    private void createControl() {
        setLayout(new FormLayout("fill:1dlu:grow, 2dlu, fill:pref:nogrow", "default"));
        add(fileField, new CellConstraints(1, 1));
        add(chooseFileButton, new CellConstraints(3, 1));
    }

    public File getFileChosen() {
        return fileChosen;
    }

    public void setReadOnly(boolean readOnly) {
        chooseFileButton.setEnabled(!readOnly);
    }

    public void setEnabled(boolean enabled) {
        chooseFileButton.setEnabled(enabled);
        fileField.setEnabled(enabled);
    }

    public void setFileChosen(File fileChosen) {
        notifyListeners(this.fileChosen, fileChosen);
        this.fileChosen = fileChosen;
        fileField.setText(fileChosen.getAbsolutePath());
    }

    public void addFileListener(PropertyChangeListener listener) {
        fileChangeListeners.add(listener);
    }

    public void removeFileListener(PropertyChangeListener listener) {
        fileChangeListeners.remove(listener);
    }

    public void notifyListeners(File oldFile, File newFile) {
        PropertyChangeEvent event = new PropertyChangeEvent(this, "fileChosen", oldFile, newFile);
        Iterator listenerIterator = fileChangeListeners.iterator();
        while (listenerIterator.hasNext()) {
            PropertyChangeListener listener = (PropertyChangeListener) listenerIterator.next();
            listener.propertyChange(event);
        }
    }

    class Handler implements ActionListener {

        public void actionPerformed(ActionEvent e) {
            int result = chooser.showOpenDialog(null);
            if (result == JFileChooser.APPROVE_OPTION) {
                setFileChosen(chooser.getSelectedFile());
            }
        }
    }
}  
